import 'package:core_package/core_package.dart';
import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/model/province_model.dart';
import 'package:flutter_app_unionad/model/work_take_model.dart';
import 'package:flutter_app_unionad/request/workbench_request.dart';
import 'package:flutter_app_unionad/ui/basice/show_select_address_dialog.dart';
import 'package:flutter_app_unionad/ui/basice/title_alert_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/promotion_input_widget.dart';
import 'package:flutter_app_unionad/ui/workbench/work_activate_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class WorkTakeListWidget extends StatefulWidget {
  @override
  _WorkTakeListWidgetState createState() => _WorkTakeListWidgetState();
}

class _WorkTakeListWidgetState extends State<WorkTakeListWidget> {
  ProvinceModel? _provinceModel;
  ProvinceModel? _cityModel;
  ProvinceModel? _areaModel;
  bool up = false;
  List<WorkTakeModel>? dataSource;
  int page = 0;
  EasyRefreshController? _controller;
  String? name;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    getData();
  }

  void getData() {
    page = 1;
    print(_cityModel);
    WorkBenchRequest.bookingList(
            pageNum: page,
            userName: name,
            timeSort: up ? 1 : 0,
            userCityCode: _cityModel != null ? _cityModel!.id.toString() : "",
            userProvinceCode: _provinceModel != null ? _provinceModel!.id.toString() : "",
            userCountyCode: _areaModel != null ? _areaModel!.id.toString() : "")
        .then((value) {
      if (value != null) {
        if (dataSource == null) dataSource = [];
        dataSource?.clear();
        dataSource?.addAll(value);
      }
      if (mounted) setState(() {});
    });
  }

  void getMoreData() {
    page++;
    WorkBenchRequest.bookingList(
      pageNum: page,
      userName: name,
      timeSort: up ? 1 : 0,
      userCityCode: _cityModel != null ? _cityModel!.id.toString() : "",
      userProvinceCode: _provinceModel != null ? _provinceModel!.id.toString() : "",
      userCountyCode: _areaModel != null ? _areaModel!.id.toString() : "",
    ).then((value) {
      if (value != null) {
        if (dataSource == null) dataSource = [];
        dataSource?.addAll(value);
      }
      if (dataSource != null && dataSource!.length < 20) {
        _controller!.finishLoadCallBack?.call();
      } else {
        _controller!.resetLoadStateCallBack?.call();
      }
      if (mounted) setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        buildTopWidget(),
        SizedBox(height: 5.px),
        Expanded(child: buildListView()),
      ],
    );
  }

  Widget buildListView() {
    if (dataSource == null) {
      return ProgressDialog.showFirstLoading();
    }
    if (dataSource!.length == 0) {
      return Container(
        color: MyColors.color_246_244_239,
        child: EmptyWidget(),
      );
    }
    return Container(
      color: MyColors.color_246_244_239,
      child: EasyRefresh(
        header: RefreshBasics.header,
        footer: RefreshBasics.footer,
        controller: _controller,
        onRefresh: () async {
          getData();
        },
        onLoad: () async {
          getMoreData();
        },
        child: ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: dataSource!.length,
          itemBuilder: (ctx, index) {
            return buildItem(index);
          },
        ),
      ),
    );
  }

  String? remark;

  Widget buildItem(int index) {
    String address = dataSource![index].userProvince! +
        dataSource![index].userCity! +
        dataSource![index].userCounty! +
        dataSource![index].userAddress!;
    return Column(
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 20.px, vertical: 15.px),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5.px),
          ),
          child: Column(
            children: [
              buildRowItem('take_address', address, Size(11, 13)),
              MySizeBox(height: 5),
              buildRowItem(
                  'take_info', "${dataSource![index].userName ?? ""} : ${dataSource![index].userTel}", Size(11, 9)),
              MySizeBox(height: 5),
              buildRowItem('take_time', "预约时间 : ${dataSource![index].createTime ?? ""}", Size(12, 12)),
              MySizeBox(height: 5),
              dataSource![index].status == "01"
                  ? Row(
                      children: [
                        Expanded(child: SizedBox()),
                        buildButton(
                            title: '激活',
                            onTop: () {
                              print(dataSource![index].toJson());
                              NavigatorUtil.push(context, WorkActivatePage.routeName, arguments: dataSource![index])
                                  .then((value) => getData());
                            }),
                        MySizeBox(width: 10.px),
                        buildButton(
                          title: '取消安装',
                          onTop: () {
                            ShowCenterAlertDialog.showAlert(context, builder: (ctx) {
                              return PromotionInputWidget(
                                title: '取消安装输入备注',
                                onTap: (value, devId) {
                                  //
                                  if (value.length == 0) {
                                    ShowToastWidget.showToast(msg: '请输入备注');
                                    return;
                                  }
                                  remark = value;
                                  Navigator.pop(context, true);
                                },
                                keyboardKey: TextInputType.text,
                              );
                            }, width: 335.px, height: 210.px)
                                .then((v) {
                              if (v != null && v) {
                                ProgressDialog.showProgress(context);
                                WorkBenchRequest.cancleBooking(id: dataSource![index].id, remark: remark).then((value) {
                                  ProgressDialog.dismiss(context);
                                  if (value) {
                                    page = 0;
                                    getData();
                                  }
                                });
                              }
                            });
                          },
                        ),
                      ],
                    )
                  : Container(),
            ],
          ),
        ),
        Container(
          height: 5.px,
          color: MyColors.color_246_244_239,
        )
      ],
    );
  }

  Widget buildButton({String? title, Function()? onTop}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTop,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.px),
          border: Border.all(color: MyColors.color_27_27_27, width: 0.5),
        ),
        alignment: Alignment.center,
        child: Text(
          title ?? '',
          style: TextStyle(color: MyColors.color_27_27_27, fontSize: MyFont.font11),
        ),
      ),
    );
  }

  Widget buildRowItem(String icon, String title, Size size) {
    return Row(
      children: [
        MyAssetImage(
          icon,
          width: size.width.px,
          height: size.height.px,
        ),
        MySizeBox(width: 15),
        Expanded(
          child: Text(
            title,
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontSize: MyFont.font12,
            ),
          ),
        )
      ],
    );
  }

  Widget buildTopWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        children: [
          buildSearchWidget(),
          buildTitleWidget(),
        ],
      ),
    );
  }

  Widget buildSearchWidget() {
    return Container(
      margin: EdgeInsets.only(
        left: 20.px,
        right: 20.px,
        top: 15.px,
      ),
      decoration: BoxDecoration(
        border: Border.all(color: MyColors.color_27_27_27, width: 0.5),
        borderRadius: BorderRadius.circular(5),
      ),
      child: ShowTitleInputListWidget(
        padding: EdgeInsets.zero,
        textFieldHeight: 33.px,
        textAlign: TextAlign.left,
        placeholder: "搜索关键词",
        placeholderStyle: TextStyle(color: MyColors.formHex("#CDCDCDFF"), fontSize: MyFont.font12),
        inputStyle: TextStyle(color: MyColors.color_27_27_27, fontSize: MyFont.font12),
        inputTextTapChange: (value) {
          page = 0;
          name = value;
          getData();
        },
        titleWidget: Container(
          width: 40.px,
          height: 33.px,
          child: Center(
            child: MyAssetImage(
              "take_search",
              width: 12.px,
              height: 12.px,
            ),
          ),
        ),
      ),
    );
  }

  Widget buildTitleWidget() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.px, vertical: 15.px),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () => selectCity(),
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: _provinceModel != null
                          ? /*_provinceModel.name +*/ _cityModel!.name! + " " + _areaModel!.name!
                          : "全部区域",
                      style: TextStyle(
                        color: MyColors.color_27_27_27,
                        fontWeight: MyFontWeight.regular,
                        fontSize: MyFont.font13,
                      ),
                    ),
                    WidgetSpan(
                      child: Icon(Icons.arrow_drop_down, size: 15.px),
                    ),
                  ],
                ),
              ),
            ),
          ),
          SizedBox(width: 10.px),
          Container(
            color: MyColors.color_27_27_27,
            width: 1.5,
            height: 20.px,
          ),
          SizedBox(width: 10.px),
          GestureDetector(
            onTap: () {
              up = !up;
              getData();
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  "时间",
                  style: TextStyle(
                    color: MyColors.color_27_27_27,
                    fontWeight: MyFontWeight.regular,
                    fontSize: MyFont.font13,
                  ),
                ),
                SizedBox(width: 2.px),
                MyAssetImage(
                  "take_sore",
                  width: 8.px,
                  height: 8.px,
                ),
                // Icon(up ? Icons.arrow_drop_down : Icons.keyboard_arrow_up, size: 15.px),
              ],
            ),
          )
        ],
      ),
    );
  }

  void selectCity() {
    ShowSelectAddressDialog.showAddress(context, onSelected: (province, city, area) {
      _provinceModel = province;
      _cityModel = city;
      _areaModel = area;
      setState(() {});
      getData();
    });
  }
}
